//
//  ZStatusPictureView.swift
//  swift-weibo
//
//  Created by zero on 17/3/26.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

import SDWebImage
// cell可重用标识符
private let CELLID = "reuseIdentifier"
// 计算cell的间距
private let itemMargin: CGFloat = 5
// 计算cell的宽高
private let cellWH = (ScreenWidth - 2*10 - 2*itemMargin)/3

class ZStatusPictureView: UICollectionView {

    var picUrls: [ZPictureModel]?{
        
        
        didSet{
            
            //  计算际大小
            let size = dealPictureViewSize(count: picUrls!.count)
            
            // 更新配图约束
            self.snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            // 设置layout
            let layout = collectionViewLayout as! UICollectionViewFlowLayout

            if picUrls!.count == 1 {
                layout.itemSize = size
            }else{

                layout.itemSize = CGSize(width: cellWH, height: cellWH)
            }
            
            //  同步以下itemSize 和 配图的大小
            layoutIfNeeded()
            // 刷新UI
            reloadData()

        }
    }
    
    
    
    
    private func dealPictureViewSize(count: Int) -> CGSize{
        
        // 如果是一张图片
        if count == 1 {
            // 判断图片地址是否为nil
            if let thumbnail_pic = picUrls?.first?.thumbnail_pic {
                // 通过图片地址得到本地对应的图片
                let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: thumbnail_pic)
                // 判断如果image 不为nil
                if let img = image {
                    
                    // 得到图片的真实大小
                    var imgW = img.size.width
                    var imgH = img.size.height
                    // 但是新浪微博的图片 可能很窄  也可能很长
                    // 如果宽度小于80 那么久等于80
                    if imgW < 80 {
                        imgW = 80
                    }
                    // 如果高度大于150 那么久等于150
                    if imgH > 150 {
                        imgH = 150
                    }
                    return CGSize(width: imgW, height: imgH)
                }
            }
        }
        
        // 计算行数和列数
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        
        // 计算配图的宽度和长度
        let w = CGFloat(col)*cellWH + CGFloat(col - 1)*itemMargin
        let h = CGFloat(row)*cellWH + CGFloat(row - 1)*itemMargin
        
        return CGSize(width: w, height: h)
    }
    //  init方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        //  设置垂直和水平间距
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  布局
    private func setupUI(){
        

        backgroundColor = UIColor.white
        
        //  设置代理
        dataSource = self
        delegate = self
        
        
        //  注册cell
        register(ZStatusPictureViewCell.self, forCellWithReuseIdentifier: CELLID)
        
        self.snp.makeConstraints { (make) in
            
            make.size.equalTo(CGSize(width: 100, height: 100))
        }
        
    }
    
    
}
//MARK: 代理方法
extension ZStatusPictureView:UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        // 创建SDPhotoBrowser实例
        let browser = SDPhotoBrowser()
        // 原图的父控件
        browser.sourceImagesContainerView = self
        // 原图的数量
        browser.imageCount = picUrls!.count
        // 当前需要展示图片的index
        browser.currentImageIndex = indexPath.item
        // 设置代理
        browser.delegate = self
        // 展示图片浏览器
        browser.show()
    }
}

//MARK: SDPhotoBrowser代理
extension ZStatusPictureView:SDPhotoBrowserDelegate{
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at:IndexPath(item: index, section: 0)) as! ZStatusPictureViewCell
        return cell.bgImageView.image
    }

    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = ((self.picUrls![index].thumbnail_pic ?? "") as NSString).replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
}

//MARK: 数据源代理方法
extension ZStatusPictureView:UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CELLID, for: indexPath) as! ZStatusPictureViewCell
        
        cell.pictureUrlModel = picUrls![indexPath.item]
        
        return cell
    }
}

class ZStatusPictureViewCell: UICollectionViewCell {
    
    //  提供属性
    var pictureUrlModel:ZPictureModel?{
        
        didSet{

            bgImageView.sd_setImage(with: URL(string: (pictureUrlModel?.thumbnail_pic)!), placeholderImage: UIImage(named: "avatar_default_big"))
            
            if let thumbnail_pic = pictureUrlModel?.thumbnail_pic, thumbnail_pic.hasSuffix(".gif") {
                // 显示gif图片
                gifImageView.isHidden = false
            }else{
                // 隐藏gif图片
                gifImageView.isHidden = true
            }
        }
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //  布局
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //  布局
    private func setupUI(){
        
        backgroundColor = UIColor.white
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        //  添加约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        gifImageView.snp.makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }

    }
    
    //  背景图片
    lazy var bgImageView: UIImageView = {
        
        let img = UIImageView(image: UIImage(named: "avatar_default_big"))
        // 设置图片填充方式
        img.contentMode = .scaleAspectFill
        // 超出部分不显示
        img.clipsToBounds = true
        return img
    }()
    
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
